<?php

namespace App\Models\video;

use App\Library\UpTools;
use Illuminate\Database\Eloquent\Model;

// 云点播视频
class VodVideoModel extends Model
{
    protected $table = "up_vod_video"; //表名
    const CREATED_AT = null;
    const UPDATED_AT = null;
    static $havingData;

    public static function transferField($data){
        if(!$data){
            return [];
        }
        $data = UpTools::transferFields($data);
        if(isset($data[0])){
            foreach ($data as $k => $item){
                if (isset($item["videoUrlList"])) {
                    $data[$k]["videoUrlList"] = json_decode($item["videoUrlList"], true);
                }
                if (!empty($item["createTime"])) {
                    $data[$k]["createTime"] = date("Y-m-d H:i", $item["createTime"]);
                }
                if (!empty($item["updateTime"])) {
                    $data[$k]["updateTime"] = date("Y-m-d H:i", $item["updateTime"]);
                }
                if (array_key_exists("coverImgId", $item)) {
                    $data[$k]["coverImgUrl"] = UpTools::processingPictures($item["coverImgId"]);
                }
                if (isset($item["broadcasterId"])) {
                    if(isset(self::$havingData["broadcaster"][$item["broadcasterId"]])){
                        $data[$k]["broadcasterName"] = self::$havingData["broadcaster"][$item["broadcasterId"]];
                    }else {
                        $data[$k]["broadcasterName"] = self::$havingData["broadcaster"][$item["broadcasterId"]] = BroadcasterModel::getValue("name", ["id" => $item["broadcasterId"]]);
                    }
                }
                if(array_key_exists("catId", $item)){
                    if(!isset(self::$havingData["cat"][$item["catId"]])){
                        self::$havingData["cat"][$item["catId"]] = CatModel::getValue("name", ["id" => $item["catId"]]);
                        self::$havingData["cat"][$item["catId"]] = self::$havingData["cat"][$item["catId"]] ?: "默认";
                    }
                    $data[$k]["catName"] = self::$havingData["cat"][$item["catId"]];
                }
            }
        }else {
            if (!empty($data["videoUrlList"])) {
                $data["videoUrlList"] = json_decode($data["videoUrlList"], true);
            }
            if (!empty($data["createTime"])) {
                $data["createTime"] = date("Y-m-d H:i", $data["createTime"]);
            }
            if (!empty($data["updateTime"])) {
                $data["updateTime"] = date("Y-m-d H:i", $data["updateTime"]);
            }
            if (array_key_exists("coverImgId", $data)) {
                $data["coverImgUrl"] = UpTools::processingPictures($data["coverImgId"]);
            }
            if (isset($data["broadcasterId"])) {
                $data["broadcasterName"] = BroadcasterModel::getValue("name", ["id" => $data["broadcasterId"]]);
            }
            if(array_key_exists("catId", $data)){
                $data["catName"] = CatModel::getValue("name", ["id" => $data["catId"]]);
                $data["catName"] = $data["catName"] ?: "默认";
            }
        }
        return $data;
    }

    //分页获取所有字段数据
    public static function getList($field = '*', $filter = [], $page = 1, $limit = 10, $order = "create_time", $sort = "desc"){
        $db = self::query()->where($filter)->select(is_array($field) ? $field : explode(",", $field));
        $data['count'] = $db->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$limit);
        $data['list'] = $db->skip(($page - 1) * $limit)->take($limit)->orderBy($order, $sort)->get();
        if($data['list']){
            $data['list'] = self::transferField($data['list']->toArray());
        }
        return $data;
    }

    //添加
    public static function toAdd($data, $getId=false){
        if(!$data)
            return true;
        $data["mall_id"] = request()->mallData["id"];
        if(empty($data["create_time"])) $data["create_time"] = time();
        if ($getId) {
            return  self::query()->insertGetId($data);
        } else {
            return  self::query()->insert($data);
        }
    }

    //更新
    public static function doUpdate($data, $filter = []){
        if(!$data)
            return true;
        if(empty($data["update_time"])) $data["update_time"] = time();
        $res = self::query()->where($filter)->update($data);
        if($res || $res === 0){
            return true;
        }else{
            return false;
        }
    }

    //获取多字段数据
    public static function getFields($field, $filter = [], $one = true, $toArray = true){ //缓存方法：缓存所有字段，只返回需要的字段
        if($one){
            $data = self::query()->where($filter)->select(is_array($field) ? $field : explode(",", $field))->first();
            return $data ? ($toArray ? self::transferField($data->toArray()) : UpTools::transferFields($data->toArray())) : [];
        }else{
            $data = self::query()->where($filter)->select(is_array($field) ? $field : explode(",", $field))->get()->toArray();
            return $data ? ($toArray ? self::transferField($data) : UpTools::transferFields($data)) : [];
        }
    }

    //根据ID删除数据
//    public static function delById($id){
//        $temp = self::getFields("id,vid,broadcaster_id", ["id" => $id], true, false);
//        $result = self::query()->where("id", $id)->delete();
//        return $result;
//    }

    //根据ID删除数据
    public static function delByFilter($filter){
        $temp = self::getFields("id,vid,broadcaster_id,type", $filter, false, false);
        $result = self::query()->where($filter)->delete();
        foreach ($temp as $item){
            VodApis::getInstance()->deleteMedia($item["vid"]);
            BroadcasterModel::doUpdate(["video_count" => VodVideoModel::query()->where("broadcaster_id", $item["broadcasterId"])->count()], ["id" => $item["broadcasterId"]]);
            if($item["type"] == '1') {
                $playTemp = PlayListModel::getFields("id,class_id,video_id", ["video_id" => $item["id"]], false, false);
                foreach ($playTemp as $i) {
                    PlayListModel::delById($i["id"], $i);
                }
            }else{
                CourseCatalogModel::delByFilter(["broadcaster_id" => $item['broadcasterId'], "video_id" => $item["id"]]);
            }
            PlayedRecordModel::delByFilter(["video_id" => $item["id"]]);
            CommentModel::delByFilter(["belong_id" => $item["id"], "type" => 1]);
            DynamicModel::delByFilter(["belong_id" => $item["id"], "type" => 2]);
            OperateModeModel::del(["belong_id" => $item["id"], "type" => 4]);
        }
        return $result;
    }
}
